﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using Dapper;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using SHRMS.Account;
using System.Diagnostics;

namespace SHRMS
{
    public partial class Form_Account : Form
    {
        private IDbConnection _dbConnection;
        public Form_Account()
        {
            InitializeComponent();
            _dbConnection = new DbFactory().DefaultDbConnection;
        }

        [DllImport("user32.dll")]//拖动无窗体的控件
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        private void panelTitleBar_MouseDown(object sender, MouseEventArgs e)
        {
            //拖动窗体
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="text">待加密的字符串</param>
        /// <returns></returns>
        private string MD5Encoding(string text)
        {
            byte[] TxtByte = Encoding.Default.GetBytes(text);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(TxtByte);
            return BitConverter.ToString(output).Replace("-", "");
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btn_minsize_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        private void btn_close_MouseMove(object sender, MouseEventArgs e)
        {
            this.btn_close.ForeColor = Color.Red;
        }

        private void btn_close_MouseLeave(object sender, EventArgs e)
        {
            this.btn_close.ForeColor = Color.FromArgb(47, 101, 189);
        }

        private void label_register_Click(object sender, EventArgs e)
        {
            this.tabControl_Account.SelectedIndex = 1;
        }

        private void label_login_Click(object sender, EventArgs e)
        {
            this.tabControl_Account.SelectedIndex = 0;
        }

        private void label_sign_MouseHover(object sender, EventArgs e)
        {
            this.label_login.ForeColor = Color.FromArgb(0, 0, 64);
            this.label_register.ForeColor = Color.FromArgb(0, 0, 64);
        }
        private void label_sign_MouseLeave(object sender, EventArgs e)
        {
            this.label_login.ForeColor = Color.FromArgb(47, 101, 189);
            this.label_register.ForeColor = Color.FromArgb(47, 101, 189);
        }


        private void btn_login_Click(object sender, EventArgs e)
        {
            string userid=string.Empty,
                uname = textBox_username.Text;
            string upwd = MD5Encoding(textBox_password.Text);//默认密码：12345678
            string sql = $"select userid from t_user where username = '{uname}' and password = '{upwd}'";
            try
            {
                userid = _dbConnection.QueryFirstOrDefault<string>(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"错误提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            if (string.IsNullOrEmpty(userid))
            {
                MessageBox.Show("您输入的用户名或密码有误，请确认后再试！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                Form_Main form_Main = new Form_Main(userid);
                this.Hide();
                form_Main.Show();
            }
        }

        private void btn_register_Click(object sender, EventArgs e)
        {
            string name_r = textBox_Rusername.Text;
            string pwd01_r = textBox_Rpwd01.Text;
            string pwd02_r = textBox_Rpwd02.Text;
            string email_r = textBox_Remail.Text;
            string sql_name = "SELECT COUNT(*) FROM t_user WHERE username=@username";
            string sql_email = "SELECT COUNT(*) FROM t_user WHERE email=@email";
            if (name_r == "" || pwd01_r == "" || pwd02_r == "" || email_r == "")
            {
                MessageBox.Show("检查数据合法性", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (pwd01_r.Length < 8)
            {
                MessageBox.Show("密码长度应在8~16位之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (_dbConnection.QueryFirstOrDefault<int>(sql_name, new { username = name_r }) > 0)
            {
                MessageBox.Show("用户名已存在，请修改后重试！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (_dbConnection.QueryFirstOrDefault<int>(sql_email, new { email = email_r }) > 0)
            {
                MessageBox.Show("邮箱已被使用，请修改后重试！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (!Regex.IsMatch(email_r, @"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", RegexOptions.IgnoreCase))
            {
                // Match attempt failed
                MessageBox.Show("请输入正确的邮箱地址！", "邮箱地址不合法", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                // Successful match
                if (pwd01_r == pwd02_r)
                {
                    string pwd = MD5Encoding(pwd01_r);

                    string sql_str = $"insert into t_user(userid,username,password,email,role) values('{Guid.NewGuid():N}','{name_r}','{pwd}','{email_r}','游客');";
                    try
                    {
                        var result = _dbConnection.Execute(sql_str);
                        if (result > 0)
                        {
                            MessageBox.Show("注册成功！快去登录吧！", "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            throw new Exception("请检查后重试！");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"注册失败，{ex.Message}", "注册提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("您两次输入的密码不相同，请确认后再试！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
        }

        private void btn_Settings_Click(object sender, EventArgs e)
        {
            using (Form_AppSettings form_AppSettings = new Form_AppSettings())
            {
                if (form_AppSettings.ShowDialog()==DialogResult.OK)
                {
                    _dbConnection = new DbFactory().DefaultDbConnection;
                }
            }
        }

        private void Exit_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void About_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("https://gitee.com/tzm22270969436/shrms");
        }
    }
}
